package com.example.statemachine.domain.state.cola.statemachine;

import com.alibaba.cola.statemachine.builder.StateMachineBuilder;
import com.alibaba.cola.statemachine.builder.StateMachineBuilderFactory;
import com.example.statemachine.domain.enums.CreditOrderAction;
import com.example.statemachine.domain.enums.CreditOrderEvent;
import com.example.statemachine.domain.enums.CreditOrderStatus;
import com.example.statemachine.domain.state.cola.handler.ApplyAuditHandler;
import com.example.statemachine.domain.state.cola.handler.ApprovalAuditHandler;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

@Component("creditOrderStateMachineFactory")
public class CreditOrderStateMachineFactory extends AbstractStateMachineFactory<CreditOrderStatus, CreditOrderAction,CreditOrderContext>{
    @Resource
    private ApplyAuditHandler applyAuditHandler;
    @Resource
    private ApprovalAuditHandler approvalAuditHandler;

    @PostConstruct
    @Override
    protected void init() {
        StateMachineBuilder<CreditOrderStatus,CreditOrderAction,CreditOrderContext> builder = StateMachineBuilderFactory.create();
        //提交审核：INIT->AUDITING
        builder.externalTransition()
                .from(CreditOrderStatus.INIT)
                .to(CreditOrderStatus.AUDITING)
                .on(CreditOrderAction.APPLY_AUDIT)
                .when(context -> applyAuditHandler.isSatisfied(context))
                .perform((from,to,action,context) -> applyAuditHandler.execute(from,to,action,context));
        //审核通过：AUDITING->PASSED
        builder.externalTransition()
                .from(CreditOrderStatus.AUDITING)
                .to(CreditOrderStatus.PASSED)
                .on(CreditOrderAction.APPROVAL_AUDIT)
                .when(context -> approvalAuditHandler.isSatisfied(context))
                .perform((from,to,action,context) -> approvalAuditHandler.execute(from,to,action,context));
        builder.build(getMachineId());
    }

    @Override
    protected String getMachineId() {
        return "statemachine:cola:creditOrder";
    }
}
